<template>
  <div class="content">
    <div class="left">
      <div class="text">
        <p class="title">
          {{ title }}
        </p>
        <el-divider style="margin: 0" />
        <div style="height: calc(100vh - 61px - 30px)">
          <el-scrollbar height="100%">
            <div class="list" v-if="currentItem.originJson">
              <div class="item" v-for="(item, index) in currentItem.originJson.context" :key="index">
                <span>{{ index + 1 }}.</span>
                {{ item.text }}
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <el-divider direction="vertical" style="height: 100%; margin: 0" />
    <div class="right">
      <div class="question_list">
        <el-tabs class="tabs" v-model="activeName">
          <el-tab-pane v-for="item in tabs" :key="item.id" :label="`${item.name}【${['requestion', 'reanswer', 'retype'].includes(item.id) ? (resultTypes[item.id]?.length||0):resultTypes[item.id].length}】`" :name="item.id">
              <el-scrollbar ref="scrollbarRef">
                <div class="outer" v-if="['requestion', 'reanswer', 'retype'].includes(activeName)">
                  <div class="inner">
                    <p class="questionItem origin" v-for="(question, index) in resultTypes[activeName]" :key="getHash(question)">
                      <span>{{ index + 1 }}.</span>
                    <p class="question">问题：{{ question.original.question }}</p>
                    <p class="answer">回答：{{ question.original.answer }}</p>
                    <p class="question_type">问题类型：<el-tag>{{ question.original.question_type }}</el-tag></p>
                    </p>
                  </div>
                  <div class="inner">
                    <p class="questionItem new" v-for="(question, index) in resultTypes[activeName]" :key="getHash(question)">
                      <span>{{ index + 1 }}.</span>
                    <p class="question">问题：{{ question.new.question }}</p>
                    <p class="answer">回答：{{ question.new.answer }}</p>
                    <p class="question_type">问题类型：<el-tag>{{ question.new.question_type }}</el-tag></p>
                    </p>
                  </div>
                </div>
                <div class="outer" v-else>
                  <div class="inner">
                    <p class="questionItem origin" v-for="(question, index) in resultTypes[activeName]" :key="getHash(question)">
                      <span>{{ index + 1 }}.</span>
                    <p class="question">问题：{{ question.question }}</p>
                    <p class="answer">回答：{{ question.answer }}</p>
                    <p class="question_type">问题类型：<el-tag>{{ question.question_type }}</el-tag></p>
                    </p>
                  </div>
                </div>
              </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-divider style="margin: 0" />
      <div class="form">
        <el-form label-suffix="：" @submit.prevent>
          <!-- <el-form-item label="问题">
            <el-input v-model="form.question" type="textarea" placeholder="请输入问题" :rows="2"
              @keyup.enter.ctrl.prevent="onSubmit" />
          </el-form-item>
          <el-form-item label="回答">
            <el-input v-model="form.answer" type="textarea" placeholder="请输入回答" :rows="2"
              @keyup.enter.ctrl.prevent="onSubmit" />
          </el-form-item>
          <el-form-item label="问题类型">
            <el-select v-model="form.question_type" placeholder="请选择问题类型" size="large">
              <el-option v-for="item in questionTypes" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <div class="tools">
              <!-- <div>
                <el-button type="primary" @click="onSubmit"> 提交 </el-button>
              </div> -->
              <div>
                <el-button @click="onPrevious"> 上一页 </el-button>
                <el-button @click="onNext"> 下一页 </el-button>
                <el-button @click="onJump"> 跳转到 </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {  ElMessage, ElMessageBox } from "element-plus";
import { computed, onBeforeUnmount, onMounted, PropType, ref, watch } from "vue";
import { IJsonDataContext, IQa, QuestionType } from "@/types/question";
import { IElScrollBar } from "@/types/element-plus";

const props = defineProps({
  originJson: {
    type: Array as PropType<IJsonDataContext[]>,
    default: () => []
  },
  newJson: {
    type: Array as PropType<IJsonDataContext[]>,
    default: () => []
  }
})

const getHash = (value: {
  question: string,
  answer: string,
  question_type: QuestionType
}) => {
  return `##${value.question}##${value.answer}##${value.question_type}##`;
}

const activeName = ref('not_edit')
const tabs = ref([
  {
    id: 'not_edit',
    name: '未修改'
  },
  {
    id: 'deleted',
    name: '已删除'
  },
  {
    id: 'added',
    name: '新增'
  },
  {
    id: 'requestion',
    name: '修改问题'
  },
  {
    id: 'reanswer',
    name: '修改回答'
  },
  {
    id: 'retype',
    name: '修改问题类型'
  }
])

const resultTypes = computed(() => {

  // 初始化比较结果
  const result: {
    not_edit: IQa[]
    deleted: IQa[],
    added: IQa[],
    requestion: {
      original: IQa,
      new: IQa
    }[],
    reanswer: {
      original: IQa,
      new: IQa
    }[]
    retype: {
      original: IQa,
      new: IQa
    }[],
  } = {
    not_edit: [],
    deleted: [],
    added: [],
    requestion: [],
    reanswer: [],
    retype: []
  }

  //  创建双向映射字典（使用整个对象哈希值作为标识）
  const original_map = new Map(currentItem.value.originJson?.qaList.map(e => {
    return [getHash(e), e]
  }) || [])

  const new_map = new Map(currentItem.value.newJson?.qaList.map(e => [getHash(e), e]) || [])

  // 找出完全删除的条目（哈希值在original但不在new）
  original_map.forEach((value, key) => {
    if (!new_map.has(key)) {
      result.deleted.push(value)
    }
  })
  // 找出完全新增的条目（哈希值在new但不在original）
  new_map.forEach((value, key) => {
    if (!original_map.has(key)) {
      result.added.push(value)
    }
  })
  // 找出可能修改的条目（字段变化但哈希值不同）
  const newValues = Array.from(new_map.values())
  const originValues = Array.from(original_map.values())
  for (let i = 0; i < newValues.length; i++) {
    let found = false
    let new_item = newValues[i]
    for (let j = 0;  j < originValues.length;j++) {
      let orig_item = originValues[j]
      if (new_item.answer == orig_item.answer &&
        new_item.question != orig_item.question) {
        result.requestion.push({
          original: orig_item,
          new: new_item
        })
        // 从删除和新增列表移除
        if (result.deleted.map(e => getHash(e)).includes(getHash(orig_item))) {
          result.deleted.splice(result.deleted.map(e => getHash(e)).indexOf(getHash(orig_item)), 1)
        }
        if (result.added.map(e => getHash(e)).includes(getHash(new_item))) {
          result.added.splice(result.added.map(e => getHash(e)).indexOf(getHash(new_item)), 1)
        }
        found = true
        break
      }
      // 如果除answer外其他字段相同，视为重回答
      if (new_item.question == orig_item.question &&
        new_item.answer != orig_item.answer) {
        result.reanswer.push({
          original: orig_item,
          new: new_item
        })
        // 从删除和新增列表移除
        if (result.deleted.map(e => getHash(e)).includes(getHash(orig_item))) {
          result.deleted.splice(result.deleted.map(e => getHash(e)).indexOf(getHash(orig_item)), 1)
        }
        if (result.added.map(e => getHash(e)).includes(getHash(new_item))) {
          result.added.splice(result.added.map(e => getHash(e)).indexOf(getHash(new_item)), 1)
        }
        found = true
        break
      }
      // 如果除question_type外其他字段相同，视为重类型
      if (new_item.question == orig_item.question &&
        new_item.answer == orig_item.answer &&
        new_item.question_type != orig_item.question_type) {
        result.retype.push({
          original: orig_item,
          new: new_item
        })
        // 从删除和新增列表移除
        if (result.deleted.map(e => getHash(e)).includes(getHash(orig_item))) {
          result.deleted.splice(result.deleted.map(e => getHash(e)).indexOf(getHash(orig_item)), 1)
        }
        if (result.added.map(e => getHash(e)).includes(getHash(new_item))) {
          result.added.splice(result.added.map(e => getHash(e)).indexOf(getHash(new_item)), 1)
        }
        found = true
        break
      }
      if (new_item.question == orig_item.question &&
        new_item.answer == orig_item.answer &&
        new_item.question_type == orig_item.question_type) {
          result.not_edit.push(new_item)
          found = true
          break
        }
    }
    // if (found == false) {
    //   console.log(new_item)
    //   result.added.push(new_item)
    // }
  }
  return result
})

const currentContextId = ref(0)
const setCurrentContextId = (id: number) => {
  currentContextId.value = id;
};

const currentItem = computed(() => {
  return {
    originJson: props.originJson.find(e => e.context_id === currentContextId.value),
    newJson: props.newJson.find(e => e.context_id === currentContextId.value)
  };
});

const currentIndex = computed(() => {
  return props.originJson.findIndex(e => e.context_id === currentContextId.value)
});

const totalCount = computed(() => {
  return props.originJson.length;
});

const title = computed(() => {
  return `页码：${currentIndex.value + 1}/${totalCount.value}`;
});

// const form = ref<{
//   question: string;
//   answer: string;
//   question_type: QuestionType;
// }>({
//   question: "",
//   answer: "",
//   question_type: "基础问答",
// });
// const onSubmit = () => {
//   if (!form.value.question) return ElMessage.warning("请输入提问内容！");
//   if (editId.value) {
//     const index = Number(editId.value.split("$")[1]) as number;
//     piniaStore.questionStore.editQuestion({
//       index: index,
//       question: form.value.question,
//       answer: form.value.answer,
//       question_type: form.value.question_type,
//     });
//     editId.value = ''
//   }else {
//     piniaStore.questionStore.addQuestion({
//       question: form.value.question,
//       answer: form.value.answer,
//       question_type: form.value.question_type,
//     });
//   }
//   form.value = {
//     'question': '',
//     'answer': '',
//     'question_type': '基础问答'
//   }
// };

const scrollbarRef = ref<IElScrollBar[]>();
const onPrevious = () => {
  const index = props.originJson.findIndex(e => e.context_id === currentContextId.value)
  if (index > 0) {
    currentContextId.value = props.originJson[index - 1].context_id
    if(!scrollbarRef.value?.length) return
    scrollbarRef.value[tabs.value.findIndex(e => e.id === activeName.value)].setScrollTop(0)
  }else {
    ElMessage.warning('已经是第一条了')
  }
  // piniaStore.questionStore.previous();
};

const onNext = () => {
  const index = props.originJson.findIndex(e => e.context_id === currentContextId.value)
  if (index < props.originJson.length - 1) {
    currentContextId.value = props.originJson[index + 1].context_id
    if(!scrollbarRef.value?.length) return
    scrollbarRef.value[tabs.value.findIndex(e => e.id === activeName.value)].setScrollTop(0)
  }else {
    ElMessage.warning('已经是最后一条了')
  }
  // piniaStore.questionStore.next();
};

const onJump = async () => {
  const { value } = await ElMessageBox.prompt("请输入序号", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^\+?[1-9]\d*$/,
    inputErrorMessage: "请输入数字",
  });
  // piniaStore.questionStore.setNumber(Number(value));
};

const keydown = (e: KeyboardEvent) => {
    if (e.code === 'KeyA') {
      onPrevious()
    }else if(e.code === 'KeyD'){
      onNext()
    }
};

onMounted(() => {
  document.addEventListener('keydown', keydown)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', keydown)
})

// const onDelete = (index: number) => {
//   piniaStore.questionStore.deleteQuestion({
//     index: index,
//   });
//   return true;
// };

defineExpose({
  setCurrentContextId
})

// const editId = ref('');
// const onEdit = (index: number) => {
//   if (!currentItem.value) return
//   editId.value = `${currentItem.value.context_id}$${index}`
//   const item = currentItem.value?.qaList[index];
//   if (!item) return
//   // form.value = {
//   //   question: item.question,
//   //   answer: item.answer,
//   //   question_type: item.question_type,
//   // }
//   form.value.question = item.question
//   form.value.answer = item.answer
//   form.value.question_type = item.question_type
// };
</script>

<style scoped lang="scss">
.content {
  width: 1300px;
  height: calc(100vh - 61px);
  margin: 0 auto;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
  display: flex;

  .left {
    width: 30%;
    height: calc(100vh - 61px);

    .text {
      height: calc(100vh - 61px);
      font-size: 16px;
      line-height: 1.5;
      text-indent: 2em;

      .title {
        font-size: 16px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        color: #67c23a;
      }

      .text_inner {
        padding: 20px;
      }
    }

    .list {
      padding: 0 20px;

      .item {
        margin-bottom: 10px;
        font-size: 16px;
      }
    }
  }

  .right {
    width: 70%;
    height: 100%;

    .question_list {
      height: calc(100% - 74px - 12px);
      padding: 10px;
      :deep(.tabs){
        height: 100%;
        .el-tabs__content{
          height: calc(100% - 60px);
        }
        .el-tab-pane{
          height: 100%;
        }
      }

      .outer {
        height: calc(100% - 74px - 12px - 20px);
        display: flex;
      }

      .inner {
        padding: 16px;
        width: 50%;

        .questionItem {
          width: 100%;
          line-height: 1.5;
          padding: 6px 0;
          word-break: break-all;
          cursor: pointer;
          padding: 4px;
          position: relative;

          &:hover {
            opacity: 0.8;
            background-color: rgba($color: #000000, $alpha: 0.1);
          }

          span {
            margin-right: 10px;
          }

          .delete {
            color: #e6a23c;
            position: absolute;
            right: 0;
            top: 0;
          }

          .edit {
            color: #409EFF;
            position: absolute;
            right: 20px;
            top: 0;
          }

          .question {
            margin-bottom: 10px;
          }

          .answer {
            margin-bottom: 10px;
          }

          .question_type {
            margin-bottom: 10px;
          }
        }
      }
    }

    .form {
      height: 74px;
      padding: 20px;

      .tools {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>
